<template>
  <view class="page-wrapper">
    <u--form labelPosition="left" ref="formRef" label-width="70px" :model="shipping" :labelStyle="labelStyle">
      <view class="item">
        <view class="car-item">
          <view class="car-content">
            <u-form-item prop="name" label="联系人">
              <u--input placeholder="输入收获人姓名" border="bottom" v-model="shipping.name"></u--input>
            </u-form-item>
          </view>
        </view>
        <view class="car-item">
          <view class="car-content">
            <u-form-item prop="tel" label="联系电话">
              <u--input placeholder="输入手机号" border="bottom" v-model="shipping.tel"></u--input>
            </u-form-item>
          </view>
        </view>
        <view class="car-item">
          <view class="car-content">
            <picker @change="chooseregion" mode="region">
              <u-form-item prop="address" label="所在地区">
                <u--textarea placeholder="选择所在省份、城市、区县" border="bottom" v-model="shipping.address" autoHeight :readonly="true"></u--textarea>
              </u-form-item>
              <view class="car-icon"><u-icon name="arrow-right"></u-icon></view>
            </picker>
          </view>
        </view>
        <view class="car-item">
          <view class="car-content">
            <u-form-item prop="addressDetail" label="地址">
              <u--textarea placeholder="街道、楼牌号等详细地址" border="none" v-model="shipping.addressDetail" autoHeight maxlength="100"></u--textarea>
            </u-form-item>
          </view>
        </view>
      </view>
    </u--form>
    <view class="default">
      <u-radio-group v-model="radioGroupValue" size="18px" icon-size="12px" @change="groupChange">
        <u-radio label="设为默认地址" name="设为默认地址" label-size="12px" @change="radioChange"></u-radio>
      </u-radio-group>
    </view>
    <view class="action-wrapper action-bottom" v-if="type==='add'">
      <u-button text="保存" color="#CF1A1B" @click="handleAction"></u-button>
    </view>
    <view class="action-wrapper action-mutiple-bottom" v-if="type==='edit'">
      <u-button text="删除" color="#CF1A1B" :plain="true" @click="show=true"></u-button>
      <u-button text="保存" color="#FFFFFF" :customStyle="{background:'#CF1A1B'}"
        @click="handleAction('save')"></u-button>
    </view>
    <u-modal
    	:show="show" 
    	title="确定要删除该收货人信息吗？" 
    	:showCancelButton="true" 
    	cancelText="取消" 
    	confirmText="确定" 
    	confirmColor="#CF1A1B" 
    	@confirm="handleAction('delete')"
    	@cancel="show=false"
    >
    </u-modal>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        type: '',
        labelStyle: {
          'fontSize': '28rpx',
          'fontWeight': '400',
          'color': 'rgba(0,0,0,0.65)'
        },
        shipping: {
          name: "",
          tel: "",
          address: "",
          addressDetail: "",
        },
        radioGroupValue: '', //当前 radioGroup 选中的值
        radioValue: '', // 当前 radio 的值
        num: 0, //用于区分是否是重复选中
        // 验证规则
        rules: {
          name: {
            required: true,
            message: '请输入联系人',
            trigger: ['change', 'blur'],
          },
          tel: [{
              required: true,
              message: '请输入联系电话',
              trigger: ['change', 'blur'],
            },
            {
              validator: (rule, value, callback) => {
                return uni.$u.test.mobile(value);
              },
              message: '联系电话不正确',
              trigger: ['change', 'blur'],
            }
          ],
          address: {
            required: true,
            message: '请选择所在地区',
            trigger: ['change', 'blur'],
          },
          addressDetail: {
            required: true,
            message: '请输入详细地址',
            trigger: ['change', 'blur'],
          }
        },
        show: false
      };
    },
    methods: {
      //选择省市区
      chooseregion: function(e) {
        let code = e.detail.code
        let val = e.detail.value
        if(code && code.length === 3) {
          this.shipping.province = code[0]
          this.shipping.city = code[1]
          this.shipping.county = code[2]
        }
        if(val) {
          this.shipping.address = val.join('')
          this.$refs.formRef.validate()
        }
      },
      groupChange(n) {
        if (n == this.radioValue && this.num == 0) {
          this.num++
        } else {
          this.radioGroupValue = ''
          this.num = 0
        }
      },
      radioChange(n) {
        this.radioValue = n
        this.num = 0
      },
      async saveUpdateAddress() {
        await this.$refs.formRef.validate()
        let url = ''
        let params = {
          name: this.shipping.name,
          tel: this.shipping.tel,
          province: this.shipping.province,
          city: this.shipping.city,
          county: this.shipping.county,
          addressDetail: this.shipping.addressDetail
        }
        if (this.radioGroupValue) {
          params.isDefault = 1
        } else {
          params.isDefault = 0
        }
        if (this.type === 'add') {
          url = '/user-center/address/save'
          delete params.id
        } else {
          url = '/user-center/address/update'
          params.id = this.shipping.id
        }
        this.$request({
          method: 'POST',
          url: url,
          data: params
        }).then((res) => {
          if (res && res.respCode === 200) {
            uni.$emit('refreshAddress', '')
            uni.navigateBack()
          }
        }).catch((e) => {
          console.log('保存收获失败', e)
        })
      },
      handleAction(type) {
        if (type === 'delete') {
          this.$request({
            method: 'POST',
            url: '/user-center/address/delete',
            data: {
              ids: [this.shipping.id]
            }
          }).then((res) => {
            if (res && res.respCode === 200) {
              uni.showToast({
                title: '删除成功',
                complete: function(res) {
                  uni.$emit('refreshAddress', '')
                  setTimeout(() => {
                    uni.navigateBack()
                  }, 500)
                }
              })
            }
          }).catch((e) => {
            console.log('保存收获失败', e)
          })
        } else {
          this.saveUpdateAddress()
        }
      },
    },
    onReady() {
      this.$refs.formRef.setRules(this.rules)
    },
    onLoad(query) {
      const {
        type,
        info
      } = query
      this.type = type
      if (info) {
        let data = JSON.parse(decodeURIComponent(info));
        this.shipping = {
          ...data
        }
        this.shipping.address = `${data.provinceName}${data.cityName}${data.countyName}`
        if (data.isDefault && data.isDefault === 1) {
          this.radioGroupValue = '设为默认地址'
        } else {
          this.radioGroupValue = ''
        }
      }
      if (this.type === 'add') {
        uni.setNavigationBarTitle({
          title: '新增收获地址'
        })
        //TODO 清空表单
      } else if (this.type === 'edit') {
        uni.setNavigationBarTitle({
          title: '编辑收获地址'
        })
      }
    },
  }
</script>

<style lang="scss" scoped>
  .page-wrapper {
    .item {
      margin-bottom: 20rpx;
      background-color: #FFFFFF;
      padding-bottom: 8rpx;
      padding-top: 32rpx;

      .car-item {
        display: flex;
        margin: 0 48rpx 0 0;
        height: auto;
        align-items: center;

        .car-title {
          width: 112rpx;
          height: 28rpx;
          font-size: 28rpx;
          font-weight: 400;
          color: rgba(0, 0, 0, 0.65);
        }

        .car-content {
          flex: 1;
          margin-left: 32rpx;
          position: relative;
          font-size: 28rpx;
          font-weight: 400;
          color: rgba(0, 0, 0, 0.85);

          .car-icon {
            position: absolute;
            width: 14rpx;
            right: 0;
            bottom: 40rpx;
          }
        }

        &:last-child .car-icon {
          position: absolute;
          width: 14rpx;
          right: 20rpx;
          bottom: 0rpx;
        }
      }
    }

    .default {
      margin-top: 28rpx;
      margin-left: 32rpx;
    }

    .action-wrapper {
      height: 70px;
      width: 100%;
      position: fixed;
      bottom: 0;
      display: flex;
      align-items: center;
      background-color: #FFFFFF;
    }

    .action-bottom {
      justify-content: center;

      /deep/ .u-button {
        width: 90% !important;
      }
    }

    .action-mutiple-bottom {
      justify-content: space-evenly;

      /deep/ .u-button {
        margin: 0 32rpx;
        border-radius: 8rpx;
      }
    }
  }
</style>